using System;
using System.Threading;

namespace Gadgeteer.Interfaces.Fakes.Framework
{
    public class DelayedAction : ThreadAction
    {
        public delegate void DelayedActionAct();

        private DateTime actUntil = DateTime.MinValue;
        private DelayedActionAct action = null;

        protected DelayedAction(string threadName)
            : base(threadName)
        {
            Start();
        }

        protected override bool ActionRequired()
        {
            return action != null;
        }

        protected override void Act()
        {
            if (DateTime.Now > actUntil)
            {
                var currentAction = action;
                action = null;

                currentAction();
            }
        }

        protected void ExecuteAsDelayed(DelayedActionAct act, TimeSpan delay)
        {
            while (action != null) { Thread.Sleep(10); }

            actUntil = DateTime.Now.Add(delay);
            action = act;
        }
    }
}
